#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
typedef struct binarytree
{
	int val;
	struct binarytree* left;
	struct binarytree* right;
}BTNode;
BTNode* Buytree(int x)
{
	BTNode* node = (BTNode*)malloc(sizeof(BTNode));
	if (node == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	node->val = x;
	node->left = NULL;
	node->right = NULL;
	return node;
}
BTNode* CreateTree()
{
	BTNode* node1 = Buytree(1);
	BTNode* node2 = Buytree(2);
	BTNode* node3 = Buytree(3);
	BTNode* node4 = Buytree(4);
	BTNode* node5 = Buytree(5);
	BTNode* node6 = Buytree(6);
	BTNode* node7 = Buytree(7);
	node1->left = node2;
	node1->right = node3;
	node2->left = node4;
	node2->right = node5;
	node3->left = node6;
	node6->left = node7;
	return node1;
}
//int treesize(BTNode* root)
//{
//	if (root == NULL)
//		return 0;
//	else return treesize(root->left) + treesize(root->right) + 1;
//}

void treesize(BTNode* root,int* psize)
{
	if (root==NULL)
		return;
	++(*psize);
	treesize(root->left,psize);
	treesize(root->right,psize);
}
int treelevel(BTNode* root,int k)
{
	if (root == NULL)
		return 0;
	if (k == 1)
		return 1;
	return treelevel(root->left, k - 1) + treelevel(root->right,k-1);
}
int treeheight(BTNode* root)
{
	if (root == NULL)
		return 0;
	int left = treeheight(root->left) + 1;
	int right = treeheight(root->right) + 1;
	if (left >= right)
		return left;
	else return right;
}
void Preorder(BTNode* root)
{
	if (root == NULL)
	{
		/*perror("fail");*/
		return;
	}
	printf("%d", root->val);
	Preorder(root->left);
	Preorder(root->right);
}
BTNode* treefind(BTNode* root, int x)
{
	if (root == NULL)
		return NULL;
	if (root->val == x)
		return root;
	BTNode* l = treefind(root->left, x);
	if (l)
		return l;
	BTNode* r = treefind(root->right, x);
	if (r)
		return r;

	return NULL;

}
int main()
{
	BTNode* root = CreateTree();
	int psize = 0;
	//printf("%d",treesize(root);
	treesize(root, &psize);
	printf("%d", psize);
	printf("%d",treelevel(root, 3));
	printf("%d",treeheight(root));
	printf("\n");
	Preorder(root);
	printf("\n");
	BTNode* t=treefind(root, 5);
	printf("%d", t->val);
	return 0;
}